var start = false;
var usr = rand();
var rival = "";
var ws = new WebSocket("ws://localhost:8013");
ws.onopen = function(evt) {onOpen(evt)};
ws.onmessage = function(evt) {onMessage(evt)};
ws.onclose = function(evt) { onClose(evt) };
ws.onerror = function(evt) { onError(evt) };
sendMsg("1 " + usr);

window.onbeforeunload = function() {
    console.log("Here Close");
    ws.close();
}  

function rand() {
    var base = 100000000;
    var id = parseInt(Math.random()*base,10);
    //console.log(id); 
    return id;
}

// function login() {
//     var usr = document.getElementById("inputName").value;
//     if(!start) {
//         sendMsg("1 " + usr);
//     }
//     if(start) {
//         //window.location.href="../html/gomoku.html";
//         console.log("Login");
//     }
// }

function onOpen(evt){
    console.log("open");
    isconnect = true;
}

function onMessage(evt) {
    var str = evt.data.split(" ");
    console.log(str);
    if(parseInt(str[0]) == "1") {
        rival = str[1];
        start = true;
        // login();
    } else if(parseInt(str[0]) == "2") {
        turn = true;
        console.log("you turn!");
    } else if(parseInt(str[0]) == "3") {
        play(parseInt(str[1]),parseInt(str[2]));
    } else if(parseInt(str[0]) == "4") {
        console.log("you win!");
    } else if(parseInt(str[0]) == "5") {
        console.log("you fail!");
    } else if(parseInt(str[0]) == "6") {
        console.log("draw");
    }
}
function onClose(evt) {
    ws.close();
    console.log("close");
    console.log(evt);
}
function onError(evt) {
    console.log("error");
    console.log(evt);
}
function sendMsg(evt) {
    if(isconnect) {
        ws.send(evt);
    }
}